 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.subway.rca.dto.out.SwCkDiffAfterClearReportDTO;
import com.zdkj.subway.rca.entity.SwCkDiffAfterClearReport;
import com.zdkj.subway.rca.mapper.SwCkDiffAfterClearReportMapper;
import com.zdkj.subway.rca.service.SwCkDiffAfterClearReportService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 清分后数据差异报表
 *
 * @author stw
 * @date 2021-01-03 21:58:58
 */
@Service
public class SwCkDiffAfterClearReportServiceImpl extends ServiceImpl<SwCkDiffAfterClearReportMapper, SwCkDiffAfterClearReport> implements SwCkDiffAfterClearReportService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkDiffAfterClearReportServiceImpl.class);
    @Override
    public List<SwCkDiffAfterClearReportDTO> listSwCkDiffAfterClearReportDTO(String statisticsMonth, String operatorsName, String lineCode) {
        List<SwCkDiffAfterClearReportDTO> list = this.baseMapper.getSwCkDiffAfterClearReportDTOList(statisticsMonth,operatorsName,lineCode);
        List<SwCkDiffAfterClearReportDTO> listNew = new ArrayList<>();

        String operators = null;
        for(SwCkDiffAfterClearReportDTO obj : list){
            if(!obj.getOperators().equals(operators) && operators != null){
                SwCkDiffAfterClearReportDTO sum = getSum(operators, list);
                listNew.add(sum);
            }
            operators = obj.getOperators();
            listNew.add(obj);
        }
        if(list.size() > 0) { //最后一个运营商
            SwCkDiffAfterClearReportDTO sum = getSum(operators, list);
            listNew.add(sum);
        }
        SwCkDiffAfterClearReportDTO sumAll = getSum("合计", list);
        sumAll.setLineCode("--");
        sumAll.setLineName("--");
        listNew.add(sumAll);
        return listNew;
    }

    private SwCkDiffAfterClearReportDTO getSum(String operators,List<SwCkDiffAfterClearReportDTO> list){
        SwCkDiffAfterClearReportDTO sumSwCkDiffAfterClearReportDTO = new SwCkDiffAfterClearReportDTO();
        if(!operators.equals("合计")){
            sumSwCkDiffAfterClearReportDTO.setLineCode("小计");
            sumSwCkDiffAfterClearReportDTO.setLineName("小计");
        }
        if(operators.equals("合计")){
            sumSwCkDiffAfterClearReportDTO.setOperatorsName(operators);
            sumSwCkDiffAfterClearReportDTO.setOperators(operators);
        }
        BigDecimal lastClearMoneyDCP = new BigDecimal("0");
        BigDecimal currClearMoneyDCP = new BigDecimal("0");
        BigDecimal diffMoneyDCP = new BigDecimal("0");

        BigDecimal lastClearMoneyCAT = new BigDecimal("0");
        BigDecimal currClearMoneyCAT = new BigDecimal("0");
        BigDecimal diffMoneyCAT = new BigDecimal("0");

        BigDecimal lastClearMoneyJTK = new BigDecimal("0");
        BigDecimal currClearMoneyJTK = new BigDecimal("0");
        BigDecimal diffMoneyJTK = new BigDecimal("0");

        BigDecimal lastClearMoneyEWM = new BigDecimal("0");
        BigDecimal currClearMoneyEWM = new BigDecimal("0");
        BigDecimal diffMoneyEWM = new BigDecimal("0");

        BigDecimal lastClearMoneyRLDZ = new BigDecimal("0");
        BigDecimal currClearMoneyRLDZ = new BigDecimal("0");
        BigDecimal diffMoneyRLDZ = new BigDecimal("0");


        for(SwCkDiffAfterClearReportDTO  obj : list){
            if(operators.equals("合计") || operators.equals(obj.getOperators())){
                lastClearMoneyDCP = lastClearMoneyDCP.add(obj.getLastClearMoneyDCP());
                currClearMoneyDCP = currClearMoneyDCP.add(obj.getCurrClearMoneyDCP());
                diffMoneyDCP = diffMoneyDCP.add(obj.getDiffMoneyDCP());

                lastClearMoneyCAT = lastClearMoneyCAT.add(obj.getLastClearMoneyCAT());
                currClearMoneyCAT = currClearMoneyCAT.add(obj.getCurrClearMoneyCAT());
                diffMoneyCAT = diffMoneyCAT.add(obj.getDiffMoneyCAT());

                lastClearMoneyJTK = lastClearMoneyJTK.add(obj.getLastClearMoneyJTK());
                currClearMoneyJTK = currClearMoneyJTK.add(obj.getCurrClearMoneyJTK());
                diffMoneyJTK = diffMoneyJTK.add(obj.getDiffMoneyJTK());

                lastClearMoneyEWM = lastClearMoneyEWM.add(obj.getLastClearMoneyEWM());
                currClearMoneyEWM = currClearMoneyEWM.add(obj.getCurrClearMoneyEWM());
                diffMoneyEWM = diffMoneyEWM.add(obj.getDiffMoneyEWM());

                lastClearMoneyRLDZ = lastClearMoneyRLDZ.add(obj.getLastClearMoneyRLDZ());
                currClearMoneyRLDZ = currClearMoneyRLDZ.add(obj.getCurrClearMoneyRLDZ());
                diffMoneyRLDZ = diffMoneyRLDZ.add(obj.getDiffMoneyRLDZ());
            }
        }

        sumSwCkDiffAfterClearReportDTO.setLastClearMoneyDCP(lastClearMoneyDCP.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setCurrClearMoneyDCP(currClearMoneyDCP.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setDiffMoneyDCP(diffMoneyDCP.setScale(2,BigDecimal.ROUND_HALF_UP));

        sumSwCkDiffAfterClearReportDTO.setLastClearMoneyCAT(lastClearMoneyCAT.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setCurrClearMoneyCAT(currClearMoneyCAT.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setDiffMoneyCAT(diffMoneyCAT.setScale(2,BigDecimal.ROUND_HALF_UP));

        sumSwCkDiffAfterClearReportDTO.setLastClearMoneyJTK(lastClearMoneyJTK.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setCurrClearMoneyJTK(currClearMoneyJTK.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setDiffMoneyJTK(diffMoneyJTK.setScale(2,BigDecimal.ROUND_HALF_UP));

        sumSwCkDiffAfterClearReportDTO.setLastClearMoneyEWM(lastClearMoneyEWM.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setCurrClearMoneyEWM(currClearMoneyEWM.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setDiffMoneyEWM(diffMoneyEWM.setScale(2,BigDecimal.ROUND_HALF_UP));

        sumSwCkDiffAfterClearReportDTO.setLastClearMoneyRLDZ(lastClearMoneyRLDZ.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setCurrClearMoneyRLDZ(currClearMoneyRLDZ.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumSwCkDiffAfterClearReportDTO.setDiffMoneyRLDZ(diffMoneyRLDZ.setScale(2,BigDecimal.ROUND_HALF_UP));
        return sumSwCkDiffAfterClearReportDTO;
    }

    @Override
    public void export(String statisticsMonth,String operators,String lineCode,HttpServletResponse response) {

        List<SwCkDiffAfterClearReportDTO> records = listSwCkDiffAfterClearReportDTO(statisticsMonth,operators,lineCode);
        InputStream excelTemplateIs = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("清分后数据差异报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/SwCkDiffAfterClearReportExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("清分后数据差异报表").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出清分后数据差异报表异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
